package com.ma.serviceImp;

import com.ma.mapper.UserMapper;
import com.ma.model.Role;
import com.ma.model.User;
import com.ma.service.UserService;
import com.ma.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * author: MaHX
 * date: 2019/5/29/23:32
 * description: Spring security 权限控制登录
 **/
@Service
public class CustomUserServiceImpl implements UserDetailsService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    UserService userService;

    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        User user = userMapper.getUserAndRolesByPhone(phone);
        if (user == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        TimeUtil timeUtil = new TimeUtil();
        String recentLanded = timeUtil.getFormatDateForSix();
        userService.updateRlByUsername(recentLanded,user.getUsername());
        List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
        for(Role role : user.getRoleList()){
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
    }
}
